package adv.i31.robot;

import android.opengl.GLES20;

public class Program {

	private int programHandle;

	// Handles to shader variables
	private int mMVPMatrixHandle;
	private int mPositionHandle;

	public void use() {
		// Tell OpenGL to use this program when rendering.
		GLES20.glUseProgram(this.getProgramHandle());
	}

	public int getProgramHandle() {
		return programHandle;
	}

	public void setProgramHandle(int programHandle) {
		this.programHandle = programHandle;
	}

	public Program(VertexShader vs, FragmentShader fs) {

		// Create a program object and store the handle to it.
		programHandle = GLES20.glCreateProgram();

		if (programHandle != 0) {
			// Bind the vertex shader to the program.
			GLES20.glAttachShader(programHandle, vs.getVertexShaderHandle());

			// Bind the fragment shader to the program.
			GLES20.glAttachShader(programHandle, fs.getFragmentShaderHandle());

			// Bind attributes
			GLES20.glBindAttribLocation(programHandle, 0, "a_Position");
			GLES20.glBindAttribLocation(programHandle, 1, "a_Color");

			// Link the two shaders together into a program.
			GLES20.glLinkProgram(programHandle);

			// Get the link status.
			final int[] linkStatus = new int[1];
			GLES20.glGetProgramiv(programHandle, GLES20.GL_LINK_STATUS, linkStatus, 0);

			// If the link failed, delete the program.
			if (linkStatus[0] == 0) {
				GLES20.glDeleteProgram(programHandle);
				programHandle = 0;
			}
		}

		if (programHandle == 0) {
			throw new RuntimeException("Error creating program.");
		}

		// Set program handles. These will later be used to pass in values to
		// the program.
		setmMVPMatrixHandle(GLES20.glGetUniformLocation(programHandle, "u_MVPMatrix"));
		setmPositionHandle(GLES20.glGetAttribLocation(programHandle, "a_Position"));
	}

	public int getmMVPMatrixHandle() {
		return mMVPMatrixHandle;
	}

	public void setmMVPMatrixHandle(int mMVPMatrixHandle) {
		this.mMVPMatrixHandle = mMVPMatrixHandle;
	}

	public int getmPositionHandle() {
		return mPositionHandle;
	}

	public void setmPositionHandle(int mPositionHandle) {
		this.mPositionHandle = mPositionHandle;
	}
}
